<template>
  <div class="mobile-chat-page">
    <div class="title">
      <div class="logo-aera" v-if="logoInfo.logoEnable == 0">
        <img v-if="logoInfo.logoType == 1" :src="logoInfo.logoImg" alt="" class="company-logo" />
        <svg-icon v-else name="defaultLogo" width="0.5rem" height="0.5rem" color="white" />
      </div>
      <span class="title-text">{{ pageData.chatTitle || '在线坐席' }}</span>
    </div>

    <div class="notice-area" id="noticeArea" v-if="showNoticeList.length > 0">
      <div class="notice-scroll custom-scrollbar">
        <div
          class="notice-item"
          v-for="(item, index) in showNoticeList"
          :key="index"
          :style="{ marginTop: index == 0 ? '0' : '8px' }"
          @click="chatManager.clickNotice(item)"
        >
          <img src="../../assets/images/notice_icon.webp" class="notice-icon" />
          <span class="notice-title">{{ item.title }}</span>
          <div
            v-if="index == 0 && noticeList.length > 1 && !pageData.expendNotice"
            class="notice-more"
          >
            共&nbsp;{{ noticeList.length }}&nbsp;条
          </div>
        </div>
      </div>
      <div class="notice-fold" v-if="noticeList.length > 1">
        <img
          class="fold-icon"
          src="../../assets/images/up_arrow.webp"
          :class="pageData.expendNotice ? 'rotate-180' : ''"
          @click.stop="chatManager.changeNoticeExpendStatue()"
        />
      </div>
    </div>
    <CardInfo
      v-if="cardInfo"
      :data="cardInfo"
      page-type="mobile"
      @send="chatManager.sendParamCardMsg()"
    ></CardInfo>
    <div
      class="message-area"
      ref="loadMoreMsg"
      @scroll="chatManager.scrollEvent"
      :style="chatAutoHeight"
    >
      <ul id="chatcontent">
        <li v-for="(item, index) in chatMsgList" :key="(item.id || item.msgId) as string">
          <div
            class="message-item-area"
            v-if="item.chatPosition == MsgPosition.RIGHT || item.chatPosition == MsgPosition.LEFT"
          >
            <!-- 时间 -->
            <span class="message-time system-text left" v-if="item.chatPosition == MsgPosition.LEFT"
              >{{ chatManager.getShowName(item) }}({{ msgTimeDesc(item.createDate) }})
            </span>
            <span class="message-time system-text right" v-else
              >{{ msgTimeDesc(item.createDate) }}
            </span>
            <div
              class="message-content"
              :class="[item.chatPosition == MsgPosition.LEFT ? 'left' : 'right']"
              @mouseover="chatManager.verifyMessageTime(item)"
            >
              <el-image class="message_item_avator" :src="chatManager.getAvatarUrl(item)">
                <template #error>
                  <img
                    src="../../assets/images/avatar/agent_avatar.webp"
                    class="message_item_avator"
                  />
                </template>
              </el-image>

              <Popover
                theme="dark"
                placement="top"
                width="min-content"
                :show="
                  !!showTipMessageId &&
                  showTipMessageId == item.id &&
                  (chatManager.enableWithdraw(item) || chatManager.canCopy(item.contentType))
                "
              >
                <div
                  class="tooltip-area"
                  v-if="chatManager.enableWithdraw(item) || chatManager.canCopy(item.contentType)"
                >
                  <div
                    v-if="chatManager.canCopy(item.contentType)"
                    class="tooltip-btn"
                    @click="(e) => chatManager.copy(e, item.content)"
                  >
                    <img class="icon" :src="copyIcon" />
                    <div class="text">复制</div>
                  </div>
                  <div
                    class="tooltip-btn"
                    @click="chatManager.withDrawMessage(item.id)"
                    v-if="chatManager.enableWithdraw(item)"
                  >
                    <img class="icon" :src="withdrawIcon" />
                    <div class="text">撤回</div>
                  </div>
                </div>
                <template #reference>
                  <div
                    class="content-area agent-text angent-bubble left"
                    v-if="item.contentType == MessageType.MESSAGE_OPERATION"
                  >
                    {{ item.content }}
                    <span v-if="item.messageType == MessageType.NOTIFICATION_NO_AGENT">
                      您可以选择&nbsp;<span
                        class="message-click-area"
                        @click.stop="chatManager.clickSendOffline"
                        >发送离线消息</span
                      >
                      <span v-if="enableLeaveMessage">
                        &nbsp;或者&nbsp;
                        <span class="message-click-area" @click.stop="chatManager.clickLeaveMessage"
                          >留言</span
                        >
                      </span>
                    </span>

                    <span
                      v-else-if="
                        item.messageType == MessageType.NOTIFICATION_CUSTOM_CONTINUE_REQUEST
                      "
                      class="message-click-area"
                      @click.stop="chatManager.requestAgentAgain"
                      >&nbsp;请求客服</span
                    >

                    <span
                      v-else-if="item.messageType == MessageType.MESSAGE_REQUEST_ERROR"
                      class="message-click-area"
                      @click.stop="chatManager.requestAgentAgain"
                      >&nbsp;重新请求</span
                    >
                  </div>

                  <RobotMsg
                    v-else-if="item.messageType == 'robot'"
                    class="content-area agent-text angent-bubble"
                    :class="[item.chatPosition == MsgPosition.LEFT ? 'left' : 'right']"
                    :message="item"
                    :workGroupConfig="workGroupConfig"
                    :transferAgent="chatManager.requestAgentAgain"
                    :get-answer="chatManager.sendRobotMessage"
                  ></RobotMsg>

                  <!-- 评价消息 -->
                  <div
                    class="content-area angent-bubble flex-row"
                    :class="[item.chatPosition == MsgPosition.LEFT ? 'left' : 'right']"
                    style="padding: 0px"
                    v-else-if="
                      item.messageType == MessageType.NOTIFICATION_INVITE_RATE ||
                      item.messageType == MessageType.NOTIFICATION_INVITE_RATE_CLOSE
                    "
                  >
                    <RobotRateMsg
                      v-if="item.content === 'robot'"
                      :chatSessionId="item.chatSessionId || ''"
                      @submitRate="chatManager.submitRate"
                      page-type="mobile"
                    ></RobotRateMsg>
                    <RateMsg
                      v-else
                      :chatSessionId="item.chatSessionId || ''"
                      @submitRate="chatManager.submitRate"
                      page-type="mobile"
                    ></RateMsg>
                  </div>

                  <!-- 文字消息 -->
                  <div
                    class="content-area agent-text angent-bubble"
                    :class="[item.chatPosition == MsgPosition.LEFT ? 'left' : 'right']"
                    v-else-if="
                      item.contentType == MessageType.MESSAGE_TEXT ||
                      item.contentType == MessageType.MESSAGE_RICH ||
                      item.contentType == MessageType.MESSAGE_LINK
                    "
                    v-html="
                      item.contentType == MessageType.MESSAGE_RICH
                        ? item.content
                        : emotionData.faceReg(item.content)
                    "
                  ></div>

                  <!-- 图片消息 -->
                  <div
                    class="chat-img-content"
                    :class="[item.chatPosition == MsgPosition.LEFT ? 'left' : 'right']"
                    v-if="item.contentType == MessageType.MESSAGE_IMAGE"
                  >
                    <el-image class="chat-img" :src="item.content" :preview-src-list="[item.content]">
                      <template #placeholder>
                        <div class="image-placeholder"></div>
                      </template>

                      <template #error>
                        <div class="image-placeholder">
                          <img src="../../assets/images/image_error.webp" class="error-icon" />
                        </div>
                      </template>
                    </el-image>
                  </div>

                  <!-- 视频消息 -->
                  <div
                    class="chat-video-message"
                    :class="[item.chatPosition == MsgPosition.LEFT ? 'left' : 'right']"
                    v-else-if="item.messageType == MessageType.MESSAGE_VIDEO"
                  >
                    <video :src="item.content" class="chat-video" controls></video>
                  </div>

                  <!-- 音频消息 -->
                  <div
                    class="content-area angent-bubble"
                    style="padding: 0"
                    :class="[item.chatPosition == MsgPosition.LEFT ? 'left' : 'right']"
                    v-else-if="item.messageType == MessageType.MESSAGE_VOICE"
                  >
                    <audio-bar
                      :isPlaying="
                        playingInfo.playingMessageId == item.id &&
                        playingInfo.isPlaying &&
                        playingInfo.playingType == 'audio'
                      "
                      :progress="
                        playingInfo.playingMessageId == item.id ? playingInfo.audioProgress : 0
                      "
                      :duration="Math.ceil(item.fileMessage.length / 1000) || 60"
                      :reverse="item.chatPosition == MsgPosition.RIGHT"
                      @toggle-play="() => chatManager.playAudio(item)"
                    ></audio-bar>
                  </div>

                  <!-- 卡片/商品/订单消息 -->
                  <div
                    class="content-area"
                    style="background: white; padding: 0px"
                    :class="[item.chatPosition == MsgPosition.LEFT ? 'left' : 'right']"
                    v-else-if="
                      item.contentType == MessageType.MESSAGE_CARD ||
                      item.contentType == MessageType.MESSAGE_GOODS ||
                      item.contentType == MessageType.MESSAGE_ORDER
                    "
                  >
                    <CardMsg :item="item" :chatManager="chatManager" page-type="mobile"></CardMsg>
                  </div>

                  <!-- 文件消息 -->
                  <div
                    class="content-area angent-bubble flex-row"
                    :class="[item.chatPosition == MsgPosition.LEFT ? 'left' : 'right']"
                    v-else-if="item.contentType == MessageType.MESSAGE_FILE && item.fileMessage"
                  >
                    <a
                      :href="item.content || item.fileMessage.filePath"
                      class="href-area"
                      target="_blank"
                      :download="item.fileMessage.fileName"
                    >
                      <img
                        class="file-icon"
                        :src="
                          getIconByFileTypeOrUrl(
                            item.fileMessage.fileType,
                            item.fileMessage.fileName || item.fileMessage.filePath
                          )
                        "
                      />
                      <div class="file-name agent-text">{{ item.fileMessage.fileName }}</div>
                    </a>
                  </div>
                </template>
              </Popover>
              <img
                class="failed-icon"
                src="../../assets/images/send_failed.webp"
                v-if="item.chatPosition == MsgPosition.RIGHT && item.status == 'failed'"
                @click="chatManager.reSendMsg(index, item)"
              />
            </div>
          </div>

          <!-- 中间的系统消息 -->
          <div class="system-msg-area" v-else>
            <span class="message-time system-text">{{
              dayjs(item.createDate).format('YYYY-MM-DD HH:mm:ss')
            }}</span>

            <!-- 撤回消息提示 -->
            <div
              class="center-content system-bubble system-bubble-text center-noice"
              v-if="item.messageType == MessageType.NOTIFICATION_WITHDRAW"
            >
              <span>{{ chatManager.getShowName(item) }}&nbsp;撤回了一条消息</span>&nbsp;<span
                v-if="item.contentType == MessageType.MESSAGE_TEXT && chatManager.isSelf(item)"
                class="message-click-area"
                @click="chatManager.reEditWithdraw(item.content)"
                >重新编辑</span
              >
            </div>

            <div
              class="center-content system-bubble system-bubble-text center-noice"
              v-else-if="
                item.messageType == MessageType.NOTIFICATION_VISITOR_CLOSE ||
                item.messageType == MessageType.NOTIFICATION_AGENT_CLOSE ||
                item.messageType == MessageType.NOTIFICATION_AUTO_CLOSE ||
                item.messageType == MessageType.NOTIFICATION_TRANSFER_AGENT_CLOSE
              "
            >
              &nbsp;{{ item.content
              }}<span class="message-click-area" @click="chatManager.requestAgentAgain"
                >请求客服</span
              >
            </div>

            <!-- 队列排队消息提示 -->
            <span
              class="center-content system-bubble system-bubble-text center-noice"
              v-else-if="item.messageType == MessageType.NOTIFICATION_QUEUE"
              >{{ chatManager.getQueueMsg(item.data) }}</span
            >
            <!-- 其他提示消息 -->
            <span class="center-content system-bubble system-bubble-text center-noice" v-else>{{
              item.content
            }}</span>
          </div>
        </li>
        <li style="width: 100%; height: 10px"></li>
        <audio
          id="audio"
          ref="audioRef"
          @ended="chatManager.audioOnended"
          @timeupdate="chatManager.audioOnprogress"
        >
          <source :src="playingInfo.voiceUrl" />
        </audio>
      </ul>
    </div>

    <div class="input-area" id="inputArea">
      <div class="input-row">
        <!-- <svg-icon
          :name="startRecordFlag && enableSendFile ? 'inputKeyboard' : 'inputVoice'"
          :color="enableSend ? '#666666' : '#C7C7C7'"
          :disabled="!enableSend"
          @click="startRecord"
        ></svg-icon> -->
        <div
          name=""
          :contenteditable="enableSend"
          id="inputContent"
          class="inputContent"
          placeholder="请输入消息"
          @paste.prevent="paste"
          @keydown="lineFeed"
          @input="updateContent"
          @focus="inputFocus()"
        ></div>
        <!-- <div style="margin-left: 0.2rem; margin-right: 0.2rem" @click="showEmojiPannel()">
          <svg-icon name="inputEmoji" :color="enableSend ? '#666666' : '#C7C7C7'"></svg-icon>
        </div> -->
        
        <div @click="toggleMoreAction" v-if="!showSendBtn || startRecordFlag">
          <svg-icon name="inputMore" :color="enableSend ? '#666666' : '#C7C7C7'"></svg-icon>
        </div>

        <button class="send-btn" v-if="showSendBtn" :disabled="!enableSend" @click="checkSendMessage()">
          发送
        </button>
      </div>
      <div class="input-other" v-if="showMoreAction">
        <div class="action-line" >
          <!-- <div class="action-item" @click="selectFile('video')">
            <input type="file" accept="video/*" class="hide-input" id="videoInput" />
            <div class="action-icon-container">
              <svg-icon
                class="action-icon"
                color="#333"
                name="video"
              ></svg-icon>  
            </div>
          </div> -->

          <!-- <div class="action-item" @click="showEmojiPannel()">
            <div class="action-icon-container">
              <svg-icon
                class="action-icon"
                color="#333"
                name="inputEmoji"
              ></svg-icon>      
            </div>
          </div> -->

          <!-- <div class="action-item" @click="selectFile('image')">
            <input type="file" accept="video/*,image/*" class="hide-input" id="imageInput" />
            <div class="action-icon-container">
              <svg-icon
                class="action-icon"
                color="#333"
                name="picture"
              ></svg-icon>  
            </div>
          </div> -->

          <!-- <div class="action-item" @click="selectFile('file')">
            <input type="file" accept="*/*" class="hide-input" id="fileInput" />
            <div class="action-icon-container">
              <svg-icon
                class="action-icon"
                color="#333"
                name="folder"
              ></svg-icon>           
            </div>
          </div> -->

          <!-- <div class="action-item" @click="startRecord">
            <div class="action-icon-container">
              <svg-icon
                class="action-icon"
                color="#333"
                name="voice"
              ></svg-icon>            
            </div>
          </div> -->

          <!-- <div class="action-item" @click="chatManager.clickRate()">
            <div class="action-icon-container">
              <svg-icon
                class="action-icon"
                color="#333"
                name="collect"
              ></svg-icon>  
            </div>
          </div> -->

          <!-- <div class="action-item" @click="chatManager.clickVideo">
            <div class="action-icon-container">
              <svg-icon
                class="action-icon"
                color="#333"
                name="video"
              ></svg-icon>  
            </div>
          </div> -->

          <!-- <div class="action-item">
            <div class="action-icon-container">
              <svg-icon
                class="action-icon"
                color="#333"
                name="inputMore"
              ></svg-icon>  
            </div>
          </div> -->



          <div v-for="item in ActionSheet" :key="item.icon" class="action-item" @click="selectFile(item.icon)">
            <input v-if="item.id" :type="item.type" :accept="item.accept" class="hide-input" :id="item.id" />
            <div class="action-icon-container">
              <svg-icon
                class="action-icon"
                :color="currentAction == item.icon ? '#415AE5' : '#333'" 
                :name="item.icon"
              ></svg-icon>           
            </div>
          </div>
        </div>
       
      </div>
      <div class="emoji-panel" id="inputEmotionBox" v-show="showEmojiFlag">
        <ul>
          <li v-for="(item, index) in filteredEmotionStartMap" :key="index" @click.stop="selectEmotion(item)">
            <span
              :style="{
                backgroundPositionY: '-' + index * 30 + 'px',
                backgroundPositionX: -0
              }"
              :title="item.meaning"
            ></span>
          </li>  
        </ul>
        <div class="emoji-last-container">
          <ul>
            <li v-for="(item, index) in filteredEmotionLastMap" :key="index" @click.stop="selectEmotion(item)">
              <span
                :style="{
                  backgroundPositionY: '-' + (filteredEmotionStartMap.length + index) * 30 + 'px',
                  backgroundPositionX: -0
                }"
                :title="item.meaning"
              ></span>
            </li>
          </ul>
          <ul class="place" style="opacity: 0;">
            占位
          </ul>
        </div>
       <div class="submit-box"> 
          <van-button 
              :class="showSendBtn ? 'active-cancel-btn' : 'default-btn'" 
              type="default"
              @click="showSendBtn && clearPreviousText()"
               >
                <template #icon>
                  <img src="@/assets/images/clear_emoji.png" alt="">
                </template>
          </van-button>
          <van-button 
              :class="showSendBtn ? 'active-send-btn' : 'default-btn'"
              type="default"
              @click="showSendBtn && checkSendMessage()">
              发送
          </van-button>
       </div>
      </div>
    </div>

    <Popup
      v-model:show="showVoicePopup"
      position="bottom"
      round 
      :style="{ height: '200px'}"
      class="popup-voice"
      >
        <div class="voice-container">
          <RecordButton @send-record="sendRecord"></RecordButton>
        </div>
    </Popup>

  </div>

  <leave-message-dialog
    :show-dialog="pageData.showLeaveMessageDialog"
    dialog-type="mobile"
    :loading="pageData.sendLeaveMessageLoading"
    @closeDialog="pageData.showLeaveMessageDialog = false"
    @sendLeaveMessage="chatManager.sendLeaveMessage"
  />

  <RateDialog
    page-type="mobile"
    :survey-method="1"
    v-if="pageData.showRate"
    @close="pageData.showRate = false"
    ref="rateDialog"
    @submitRate="chatManager.submitRate"
  />

  <NoticeDialog
    v-model:show-dialog="pageData.showNoticeDialog"
    page-type="mobile"
    :notice-info="pageData.noticeInfo"
  ></NoticeDialog>

  <div class="network-tip" v-show="networkError">
    <img class="network-tip-icon" src="../../assets/images/send_failed.webp" />
    <span class="network-tip-text">当前网络不可用，请检查您的网络配置</span>
  </div>

  <MobileVideoDialog
    ref="videoDialogRef"
    :videoURL="videoURL || ''"
    @close="handleVideoDialogClose"
  ></MobileVideoDialog>

  <RobotRate ref="robotRateRef" @commit="chatManager.submitRate"></RobotRate>

</template>

<script lang="ts" setup>
import 'vant/lib/index.css';
import VConsole from 'vconsole';
import { useRoute } from 'vue-router';
let router = useRoute();
if (router.query.showConsole == '1') {
  new VConsole();
}

import LeaveMessageDialog from '@/components/leave-message-dialog/index.vue';
import NoticeDialog from '@/components/notice-dialog/notice-dialog.vue';
import RateDialog from '@/components/rate-dialog/rate-dialog.vue';
import MobileVideoDialog from '@/components/video-dialog/MobileVideoDialog.vue';
import RobotMsg from '@/views/pc/components/RobotMsg.vue';
import RobotRate from '@/views/pc/components/RobotRate.vue';
import { Popover, Popup } from 'vant';
import RecordButton from '../mobile/components/record-button.vue';

import copyIcon from '@/assets/images/chat_copy.webp';
import withdrawIcon from '@/assets/images/chat_withdraw.webp';
import { onMounted, watch, computed, ref, reactive } from 'vue';
//表情数据
import emotionData from '@/emoji';
import CardInfo from '@/views/pc/components/CardInfo.vue';
import CardMsg from '@/views/pc/components/CardMsg.vue';
import RateMsg from '@/views/pc/components/rate/RateMsg.vue';
import RobotRateMsg from '@/views/pc/components/rate/RobotRateMsg.vue';
import dayjs from 'dayjs';

// 聊天消息管理，移动/PC 端通用
import { useChatManager, VideoCallStatuType } from '@/hooks/useChatManager';

import { MessageType, MsgPosition } from '@/lib/types';

import { getIconByFileTypeOrUrl } from '@/utils/fileType';
import utils from '@/utils/utils';
import { ElMessage, ElMessageBox } from 'element-plus';

const chatManager = useChatManager({ onRequestOpenCameraMic });
const {
  workGroupConfig,
  robotRateRef,
  pageData,
  chatMsgList,
  noticeList,
  showNoticeList,
  logoInfo,
  enableSend,
  enableSendFile,
  rateDialog,
  enableLeaveMessage,
  loadMoreMsg,
  audioRef,
  playingInfo,
  videoDialogRef,
  videoCallStatus,
  videoURL,
  cardInfo,
  msgTimeDesc
} = chatManager;

/**
 * 当前展示 tip 的消息 id
 */
const showTipMessageId = ref('');

const showVoicePopup = ref(false)

const currentAction = ref('inputEmoji')

// 可以左右切换预览历史图片
// const historyImageList = ref<string[]>([])

//表情包
let emotionMap = ref(emotionData.expressionJson);

const ActionSheet = reactive([
  {
    inputType: '',
    accept: '',
    select: '',
    icon: 'inputEmoji',
    color: '',
    id: ''
  },
  {
    type: 'file',
    accept: 'video/*,image/*',
    select: 'image',
    icon: 'picture',
    color: '',
    id: 'imageInput'
  },
  {
    type: 'file',
    accept: '*/*',
    icon: 'folder',
    color: '',
    id: 'fileInput'
  },
  {
    type: '',
    accept: '',
    select: '',
    icon: 'voice',
    color: '',
    id: ''
  },
  {
    type: '',
    accept: '',
    select: '',
    icon: 'collect',
    color: '',
    id: ''
  },
  {
    type: '',
    accept: '',
    select: '',
    icon: 'video',
    color: '',
    id: ''
  },
  {
    type: '',
    accept: '',
    select: '',
    icon: 'inputMore',
    color: '',
    id: ''
  },
  
])

const networkError = ref(false);

// 历史图片数组
// watch(
//   () => chatMsgList.value.length,() => {
//      historyImageList.value = []
//      chatMsgList.value.filter(item =>{
//       if(item.contentType == 'image') {
//         historyImageList.value.push(item.content)
//       }
//     }) as unknown as string[]    
//   }
// )

const filteredEmotionStartMap = computed(() => {
  return emotionMap.value.length > 7 
    ? emotionMap.value.slice(0, emotionMap.value.length - 7)
    : emotionMap.value;
});

const filteredEmotionLastMap = computed(() => {
  return emotionMap.value.length > 8 
    ? emotionMap.value.slice(-7)
    : emotionMap.value;
});

onMounted(() => {
  chatManager.checkRoute();
  window.addEventListener('online', function () {
    networkError.value = false;
  });
  window.addEventListener('offline', function () {
    networkError.value = true;
  });
});

// 发送录音
function sendRecord(recordResult: any) {
  chatManager.sendVoice(recordResult);
}

/**
 * 发送按钮展示标记
 */
const showSendBtn = ref(false);

/**
 * 更输入内容，发送消息预知
 */
function updateContent() {
  const $inputContent = document.getElementById('inputContent');
  let text = utils.getContentText($inputContent?.innerHTML);
  showSendBtn.value = !!text && text.length > 0;
  chatManager.sendPreviewDebounce();  
}


/**
 * 点击开始录音
 */
const startRecordFlag = ref(false);

/**
 * 切换到录音模式 需要先检测录音权限
 */
function startRecord() {
  console.log(startRecordFlag.value);
  
  if (!startRecordFlag.value) {
    if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
      navigator.mediaDevices
        .getUserMedia({ audio: true })
        .then(function (stream) {
          // 获取流中的所有轨道并停止它们
          stream.getTracks().forEach(function (track) {
            track.stop();
          });
          startRecordFlag.value = true;
          showEmojiFlag.value = false;
          showVoicePopup.value = true
          countChatHeight();
        })
        .catch(() => {
          startRecordFlag.value = false;
          ElMessage.error({
            type: 'error',
            message: '获取麦克风权限失败'
          });
        });
    } else {
      ElMessage.error({
        type: 'error',
        message: '浏览器不支持 getUserMedia'
      });
    }
  } else {
    // 取消录音
    startRecordFlag.value = false;
    countChatHeight();
  }
}

/**
 * 是否显示更多操作
 */
const showMoreAction = ref(false);

/**
 * 展开/隐藏 更多操作
 */
function toggleMoreAction() {
  showMoreAction.value = !showMoreAction.value;
  if (showMoreAction.value) {
    startRecordFlag.value = false;
    showEmojiFlag.value = true;
  }else {
    showEmojiFlag.value = false;
  }
  countChatHeight();
}

//记录 eventListener  防止重复添加
const addEventList: string[] = [];

/**
 * 选择文件
 * @param type  image/video/file
 */
function selectFile(type: string) {
  currentAction.value = type
  if(type == 'inputEmoji') return showEmojiPannel() 
  if(type == 'voice') return startRecord() 
  if(type == 'collect') return chatManager.clickRate()
  if(type == 'video') return chatManager.clickVideo() 
  let selectType = type === 'picture' ? 'image' : 'file'
  if (!enableSendFile.value) return;
  let inputElement = document.getElementById(`${selectType}Input`);
  if (inputElement) {
    inputElement.click();
    if (addEventList.includes(selectType)) {
      return;
    }
    addEventList.push(selectType);
    inputElement.addEventListener('change', function (event: any) {
      chatManager.selectFile(event);
    });
  }
}


/**
 * 输入框获取焦点
 */
function inputFocus() {
  showMoreAction.value = false;
  showEmojiFlag.value = false;
}
//是否展示表情选择框
const showEmojiFlag = ref(false);

//展示表情选择框 =
function showEmojiPannel() {
  showEmojiFlag.value = true
  // if (enableSend.value || showEmojiFlag.value) {
  //   showEmojiFlag.value = !showEmojiFlag.value;
  // }
  // if (showEmojiFlag.value) {
  //   startRecordFlag.value = false;
  //   // showMoreAction.value = false;
  // }
  countChatHeight();
}

function lineFeed(event: any) {
  let send = chatManager.lineFeed(event);
  if (send) {
    showSendBtn.value = false;
  }
}

function checkSendMessage() {
  let send = chatManager.checkSendMessage();
  if (send) {
    showSendBtn.value = false;
  }
}

function clearPreviousText() {
  const $inputContent = document.getElementById('inputContent');
  let htmlString = $inputContent?.innerHTML as string
  document.getElementById('inputContent')!.innerHTML = removeLastEmotionItem(htmlString)
  let text = utils.getContentText($inputContent?.innerHTML);
  showSendBtn.value = !!text && text.length > 0;
}

function removeLastEmotionItem(htmlString: string) {
    const imgRegex = /<img class="emotion-item" src="[^"]+">/g;
    const matches = htmlString.match(imgRegex);

    if (!matches || matches.length === 0) {
        return htmlString; 
    }
    if (matches.length === 1) {
        return ""; 
    }

    const lastImg = matches[matches.length - 1];
    const lastIndex = htmlString.lastIndexOf(lastImg);
    return htmlString.substring(0, lastIndex) + htmlString.substring(lastIndex + lastImg.length);
}

function selectEmotion(item: any) {
  chatManager.selectEmotion(item);
  showSendBtn.value = true;
}

/**
 * 聊天消息高度
 */
const chatAutoHeight = ref({ height: `calc(100% - 2.5rem)` });

/**
 * 动态计算高度
 */
function countChatHeight() {
  let inputHeight = showEmojiFlag.value || showMoreAction.value ? 6.8 : 1.3;
  const noticeElement = document.getElementById('noticeArea');
  let noticeHeight = 0;
  if (noticeElement) {
    noticeHeight = noticeElement.clientHeight;
  }
  chatAutoHeight.value = {
    height: `calc(100% - ${noticeHeight}px - ${inputHeight + 1.2}rem)`
  };
  chatManager.chatcontentToBottom();
}
chatManager.setCustomCountHeight(countChatHeight);

function paste(event: any) {
  chatManager.pasteEvent(event, () => {
    showSendBtn.value = true;
  });
}

/**
 * 视频窗口关闭处理，如果视频还在通话中改为默认状态
 */
function handleVideoDialogClose() {
  const isTalking =
    videoCallStatus.value === VideoCallStatuType.Requesting ||
    videoCallStatus.value === VideoCallStatuType.Waiting ||
    videoCallStatus.value === VideoCallStatuType.Talking;
  if (isTalking) {
    videoCallStatus.value = VideoCallStatuType.Default;
  }
}

/**
 * 开启/禁用媒体设备
 *
 * @param trackSource 1 摄像头 2 麦克风 3 屏幕共享
 * @param enable 是否禁用
 */
function onRequestOpenCameraMic(soucreType: number, enable: boolean) {
  const sourceName = soucreType === 1 ? '摄像头' : '麦克风';
  ElMessageBox.confirm(`客服请求你开启${sourceName}`, `开启${sourceName}`, {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    center: true
  })
    .then(() => {
      videoDialogRef.value.openCameraMic(soucreType, enable);
    })
    .catch(() => {});
}
</script>

<style lang="scss" scoped>
.mobile-chat-page {
  width: 100vw;
  height: 100vh;
  display: flex;
  background-color: var(--color-chat-bg);
  flex-direction: column;
}

.title {
  width: 100vw;
  height: 1.2rem;
  display: flex;
  align-items: center;
  padding: 0 16px;
  flex-shrink: 0;
  box-shadow: 0px -1px #e7e7e7 inset;
  background-color: var(--color-title-bg);

  .logo-aera {
    flex-shrink: 0;
    margin-right: 0.2rem;
  }

  .company-logo {
    width: auto;
    height: 0.5rem;
    object-fit: contain;
  }

  .title-text {
    flex: 1;
    font-size: 0.4rem;
    font-weight: 500;
    color: var(--color-title-text);
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }
}

.message-item-area {
  margin-left: 12px;
  margin-right: 12px;
  margin-top: 0.4rem;
  display: flex;
  flex-direction: column;

  .message-content {
    margin-top: 0.2rem;
    font-size: 0.4rem;
    display: flex;
    line-height: 0.6rem;
    &.left {
      flex-direction: row;
      justify-content: flex-start;
    }
    &.right {
      flex-direction: row-reverse;
    }

    .failed-icon {
      width: 0.5rem;
      height: 0.5rem;
      margin-right: 0.2rem;
      align-self: center;
    }
    .message_item_avator {
      width: 0.8rem;
      height: 0.8rem;
      border-radius: 0.4rem;
      flex-shrink: 0;
      background-color: var(--color-chat-bg);
      display: inline-block;
    }

    .content-area {
      max-width: 75vw;
      line-height: 0.6rem;
      flex-shrink: 0;
      padding: 8px 12px;
      font-size: 0.4rem;
      box-sizing: border-box;
      letter-spacing: -1.5%;

      &.left {
        margin-left: 0.3rem;
        border-radius: 0px 0.2rem 0.2rem 0.2rem;
      }

      &.right {
        margin-right: 0.3rem;
        border-radius: 0.2rem 0px 0.2rem 0.2rem;
      }

      &.flex-column {
        display: flex;
        flex-direction: column;
      }

      &.flex-row {
        display: flex;
        flex-direction: row;
      }
    }

    .file-icon {
      width: 0.9rem;
      height: 0.9rem;
      align-self: center;
    }
    .file-name {
      align-self: center;
      margin-left: 0.3rem;
      max-height: 1.6rem;
      color: #333333;
      font-family: PingFang SC;
      font-size: 0.4rem;
      line-height: 0.6rem;
      overflow-wrap: break-word;
      word-break: break-all;
    }
    .chat-img-content {
      max-width: 50vw;
      min-width: 3.2rem;

      &.left {
        margin-left: 0.3rem;
      }

      &.right {
        margin-right: 0.3rem;
      }
    }

    .chat-video-message {
      max-width: 50vw;
      min-width: 3.2rem;
      position: relative;
      object-fit: contain;

      &.left {
        margin-left: 0.3rem;
      }

      &.right {
        margin-right: 0.3rem;
      }
    }
  }
}

.chat-img {
  max-width: 100%;
  height: auto;
  border-radius: 8px;

  .image-placeholder {
    width: 3.2rem;
    height: 3.2rem;
    display: flex;
    align-items: center;
    justify-content: center;
    background-color: #f1f1f1;
    border-radius: 8px;
  }

  .error-icon {
    width: 0.5rem;
    height: 0.5rem;
  }
}

.chat-video {
  max-width: 100%;
  height: 100%;
  border-radius: 8px;
}

.message-click-area {
  color: var(--color-main-theme);
  cursor: pointer;
}
.message-time {
  font-size: 0.3rem;
  height: 0.5rem;
  color: var(--color-system-text);
  font-size: 0.3rem;
  line-height: 0.5rem;

  &.left {
    margin-left: 1.1rem;
    align-self: flex-start;
  }

  &.right {
    margin-right: 1.1rem;
    align-self: flex-end;
  }
}

.system-msg-area {
  margin-top: 0.4rem;
  display: flex;
  flex-direction: column;
  align-items: center;

  .center-content {
    margin-top: 0.2rem;
    font-size: 0.35rem;
    display: flex;
    line-height: 0.6rem;
    padding: 0 12px;
    border-radius: 6px;
  }
}

.tooltip-area {
  display: flex;
  align-items: center;
  gap: 20px;
  padding: 6px 10px;

  .tooltip-btn {
    cursor: pointer;
    display: flex;
    flex-direction: row;
    align-items: center;

    .icon {
      width: 22px;
      height: 22px;
    }
    .text {
      margin-left: 6px;
      height: 22px;
      color: #ffffff;
      font-size: 14px;
      line-height: 22px;
      letter-spacing: -0.5%;
    }
  }
}

.goods-href {
  display: flex;
  flex-direction: column;

  .card-title {
    width: 100%;
    color: #333333;
    font-weight: 500;
    font-size: 14px;
    line-height: 22px;
  }
  .card-content {
    width: 100%;
    display: flex;
    margin-top: 8px;

    .goods-price {
      line-height: 20px;
      color: #666666;
      font-size: 12px;
    }

    .goods-datainfo {
      color: #666666;
      font-size: 12px;
      line-height: 18px;
      margin-left: 12px;
      letter-spacing: -1%;
    }
  }
  img {
    display: block;
    flex-shrink: 0;
    align-items: top;
    width: 56px;
    height: 56px;
  }
}

.href-area {
  display: flex;
  cursor: pointer;
}
.href-area:hover,
.href-area:active {
  background-color: transparent;
}

.message-area {
  width: 100%;
  overflow: auto;
  flex: 1;
}

.input-area {
  background-color: #f1f1f1;
  .input-row {
    display: flex;
    height: 1.3rem;
    align-items: center;
    padding: 0.2rem 0.3rem;
    box-sizing: border-box;
    grid-gap: 10px;
  }
}

.inputContent {
  outline: none;
  box-sizing: border-box;
  height: 0.9rem;
  padding: 5px;
  background: #ffffff;
  overflow-y: auto;
  font-size: 0.4rem;
  // margin-left: 0.2rem;
  flex: 1;
  border: transparent;
  caret-color: #333333;
  border-radius: 4px;
  line-height: 0.6rem;
  word-break: break-word;
}
.send-btn {
  border: none;
  width: 1.2rem;
  background-color: var(--color-main-theme);
  height: 0.7rem;
  text-align: center;
  line-height: 0.7rem;
  color: white;
  font-size: 0.3rem;
  padding: 0;
  border-radius: 4px;
}
.input-other {
  width: 100vw;
  height: max-content;
  // padding: 0.5rem;
  box-sizing: border-box;
}

.action-line {
  display: flex;
  width: 100%;
  height: 46px;
  justify-content: space-between;
  align-items: center;
  padding: 0 0.3rem;
}
.action-item {
  .action-icon-container {
    .action-icon {
      width: 100%;
      height: 100%
    }
  }
  .action-text {
    display: none;
    font-size: 0.3rem;
    height: 0.5rem;
    line-height: 0.5rem;
    color: #666666;
  }
}

.hide-input {
  display: none;
}

.emoji-panel {
  width: 100vw;
  height: 5.5rem;
  display: flex;
  flex-direction: column;
  padding: 8px;
  overflow-y: auto;
  box-sizing: border-box;
  position: relative;
}

.emoji-panel  ul {
  display: grid;
  grid-template-columns: repeat(7,1fr);
  place-items: center;
  grid-gap: 20px;
  list-style: none;
}

.emoji-panel li span {
  width: 30px;
  height: 30px;
  background: url(../../assets/images/appkefu_sprites.png);
  background-size: 30px auto;
  display: block;
}

.emoji-last-panel li span {
  width: 30px;
  height: 30px;
  background: url(../../assets/images/appkefu_sprites.png);
  background-size: 30px auto;
  display: block;
}

.emoji-last-container {
  display: flex;
  flex-wrap: no-wrap;
  grid-gap: 20px;
  margin-top: 20px !important;
  ul {
    width: calc((100% - 16px) * 4 / 7);
    display: grid;
    grid-template-columns: repeat(4,1fr);
    grid-gap: 20px;
    place-items: center;
    list-style: none;
  }
  .place {
    // grid-template-columns: repeat(3,1fr) !important;
    width: calc((100% - 16px) * 3 / 7);
    display: grid;
    grid-gap: 20px;
  }
}

.submit-box {
  position: fixed;
  bottom: 8px;
  right: 8px;
  width: calc((100% - 16px) * 3 / 7);
  box-sizing: border-box;
  height: 80px;
  display: flex;
  justify-content: center;
  align-items: center;
  grid-gap: 12px;
  .default-btn {
    width: 54px;
    height: 42px;
    box-sizing: border-box;
    font-size: 16px;
    display: flex;
    align-items: center;
    justify-content: center;
    white-space: nowrap;
    color: rgba(227, 227, 227, 1);
    padding: 0px;
    border: none !important;
    ::v-deep .van-button__icon {
      width: 21px;
      height: 20px;
      opacity: 0.2;
      img {
        width: 100%;
        height: 100%;
      }
    }
  }
  .active-cancel-btn {
    width: 54px;
    height: 42px;
    box-sizing: border-box;
    white-space: nowrap;
    ::v-deep .van-button__icon {
      width: 21px;
      height: 20px;
      opacity: 1;
      img {
        width: 100%;
        height: 100%;
      }
    }
  }
  .active-send-btn {
    width: 54px;
    height: 42px;
    box-sizing: border-box;
    white-space: nowrap;
    background: rgba(65, 90, 229, 1);
    color: #fff;
  }
}


.notice-area {
  background-color: #ececec;
  width: 100%;
  height: fit-content;
  display: flex;
  flex-direction: column;
  padding: 0.2rem;
  box-sizing: border-box;
  border-radius: 0px 0px 8px 8px;
  z-index: 99;
  box-shadow: -2px 2px 10px -1px rgba($color: #000000, $alpha: 0.12);

  .notice-scroll {
    overflow-y: auto;
    max-height: 3.1rem;
  }

  .notice-item {
    width: 100%;
    height: 0.9rem;
    border-radius: 4px;
    padding: 0rem 0.4rem;
    box-sizing: border-box;
    background-color: #ffffff;
    display: flex;
    justify-content: baseline;
    align-items: center;

    .notice-icon {
      width: 0.4rem;
      height: 0.4rem;
      flex-shrink: 0;
    }

    .notice-title {
      margin-left: 8px;
      flex-grow: 1;
      color: var(--color-text-2);
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
      font-size: 0.373rem;
      height: 0.6rem;
      line-height: 0.6rem;
    }
    .notice-more {
      margin-left: 8px;
      flex-shrink: 0;
      color: var(--color-text-2);
      font-size: 0.373rem;
      height: 0.6rem;
      line-height: 0.6rem;
    }
  }
  .notice-fold {
    width: 1.12rem;
    margin-top: 0.213rem;
    height: fit-content;
    display: inline-flex;
    flex-shrink: 0;
    border-radius: 0.213rem;
    align-self: center;
    background: #dadada;

    .fold-icon {
      width: 0.427rem;
      height: 0.427rem;
      margin: auto;
      transition: transform 0.2s ease-in-out;
    }

    .rotate-180 {
      transform: rotate(180deg);
    }
  }
}

.network-tip {
  position: fixed;
  top: 1.6rem;
  width: 90%;
  height: 1.18rem;
  padding: 0.32rem;
  border-radius: 0.16rem;
  background: #fdeaeaff;
  display: flex;
  flex-direction: row;
  align-items: center;
  left: 50%;
  transform: translateX(-50%);
  z-index: 99;

  .network-tip-icon {
    width: 0.467rem;
    height: 0.467rem;
  }
  .network-tip-text {
    margin-left: 0.2rem;
    height: 0.64rem;
    color: #383838ff;
    font-size: 0.373rem;
    line-height: 0.64rem;
  }
}

.popup-voice {
  .voice-container {
    width: 100%;
    height: 100%;
  }
}
</style>
<style lang="scss">
.el-dialog {
  --el-dialog-width: 330px !important;
  .el-dialog__header {
    font-size: 0.46rem;
  }
}
</style>
